<template>
  <div class="annotation" ref="annotationRef">
    <div class="annotation-header">
      <h3>修订记录</h3>
    </div>
    <div class="annotation-content">
      <div
        v-if="annotationList.length > 0"
        class="annotation-category"
        v-for="(item, index) in annotationList"
        :key="index">
        <div v-if="item.hide === '1'">
          <div class="category-title">{{ item.fieldLabel }}</div>
          <div class="annotation-item" v-for="(itemx, indexx) in item.revisionLogs" :key="indexx">
            <div class="user-avatar">
              <el-icon><User /></el-icon>
            </div>
            <div class="annotation-detail">
              <div class="username">{{ itemx.createUserName }}</div>
              <div class="timestamp">{{ itemx.createTime }}</div>
              <div class="annotation-text">
                <span class="old-value">
                  <el-icon class="error"><Remove /></el-icon>
                  <span class="value scroll">{{ itemx.oldValue }}</span>
                </span>
                <span class="new-value">
                  <el-icon class="success"><CirclePlus /></el-icon>
                  <span class="value scroll">{{ itemx.newValue }}</span>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="no-data">暂无修订记录</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { formBase } from './formBase.ts'
const { proxy } = getCurrentInstance()

const annotationRef = ref(null)

const props = defineProps({
  // 批注列表
  annotationList: {
    type: Array,
    default: () => [],
  },
  // 表单类型
  workFlowId: {
    type: String,
    default: '',
  },
  // 最新值
  componentRef: {
    type: Object,
    default: () => ({}),
  },
  // 旧值
  oldFormData: {
    type: Object,
    default: () => ({}),
  },
})

// 找出新旧表单更改值
const checkChange = () => {
  return new Promise((resolve, reject) => {
    let newFormData = {}
    let oldData = {}
    // 只比较 formBase 中定义的字段
    for (const key in formBase[props.workFlowId]) {
      newFormData[key] = props.componentRef?.[key]
      oldData[key] = props.oldFormData?.[key]
    }

    // 存储变更记录
    const changes = []

    // 深度比较对象函数
    const deepCompare = (newObj: any, oldObj: any, path: string = '') => {
      // 获取所有可能的键（新对象和旧对象的并集）
      const allKeys = new Set([...Object.keys(newObj || {}), ...Object.keys(oldObj || {})])

      allKeys.forEach(key => {
        const currentPath = path ? `${path}.${key}` : key
        const newValue = newObj?.[key]
        const oldValue = oldObj?.[key]
        const dictType = formBase[props.workFlowId]?.[key]?.dictType || null
        const listType = formBase[props.workFlowId]?.[key]?.type || null
        const hide = formBase[props.workFlowId]?.[key]?.hide || '1' // '1'显示 '2'隐藏

        // 跳过函数、undefined值和特殊属性
        if (typeof newValue === 'function' || typeof oldValue === 'function') {
          return
        }

        // 处理对象类型
        if (newValue && oldValue && typeof newValue === 'object' && typeof oldValue === 'object') {
          // 如果都是数组
          if (Array.isArray(newValue) && Array.isArray(oldValue)) {
            if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
              changes.push({
                field: currentPath,
                oldValue: Array.isArray(oldValue) ? oldValue.join(', ') : String(oldValue || ''),
                newValue: Array.isArray(newValue) ? newValue.join(', ') : String(newValue || ''),
                type: 'array',
              })
            }
          } else if (!Array.isArray(newValue) && !Array.isArray(oldValue)) {
            // 递归比较对象
            deepCompare(newValue, oldValue, currentPath)
          } else {
            // 类型不同（一个是数组，一个不是）
            changes.push({
              field: currentPath,
              oldValue: String(oldValue || ''),
              newValue: String(newValue || ''),
              type: 'mixed',
            })
          }
        } else {
          // 处理基本类型
          const normalizedOldValue = oldValue === null || oldValue === undefined ? '' : String(oldValue)
          const normalizedNewValue = newValue === null || newValue === undefined ? '' : String(newValue)

          if (normalizedOldValue !== normalizedNewValue) {
            changes.push({
              field: currentPath,
              oldValue: normalizedOldValue,
              newValue: normalizedNewValue,
              dictType: dictType,
              listType: listType,
              hide: hide,
            })
          }
        }
      })
    }

    // 执行比较
    deepCompare(newFormData, oldData)

    // 过滤掉空值变更和无意义的变更
    const meaningfulChanges = changes.filter(change => {
      // 过滤掉都为空的变更
      if (!change.oldValue && !change.newValue) return false
      // 过滤掉相同的值
      if (change.oldValue === change.newValue) return false
      // 过滤掉特定的系统字段
      if (change.field.includes('__') || change.field.includes('$')) return false
      return true
    })

    console.log('表单变更记录:', meaningfulChanges)

    // 格式化变更记录用于显示
    new Promise(() => {
      const formattedChanges = meaningfulChanges.map(async change => {
        if (change.listType === 'dict') {
          const dictList = await proxy.useDict(change.dictType)[change.dictType]
          return {
            formName: formBase[props.workFlowId]?.formName || '未知表单',
            fieldName: change.field,
            fieldLabel: getFieldLabel(change.field), // 获取字段中文名称
            oldValue: dictList.value.find(item => item.value === change.oldValue)?.label || change.oldValue,
            newValue: dictList.value.find(item => item.value === change.newValue)?.label || change.newValue,
            hide: change.hide,
          }
        } else {
          return {
            formName: formBase[props.workFlowId]?.formName || '未知表单',
            fieldName: change.field,
            fieldLabel: getFieldLabel(change.field), // 获取字段中文名称
            oldValue: change.oldValue,
            newValue: change.newValue,
            hide: change.hide,
          }
        }
      })
      Promise.all(formattedChanges).then(results => {
        resolve(results)
      })
    })
  })
}

// 获取字段中文标签的辅助函数
const getFieldLabel = (fieldPath: string | Object): string => {
  // 字段映射表，可以根据实际需求扩展
  const fieldLabels: any = formBase[props.workFlowId] || {}
  const fieldLabelC =
    Object.prototype.toString.call(fieldLabels[fieldPath]) === '[object Object]'
      ? fieldLabels[fieldPath].name
      : fieldLabels[fieldPath]
  // 尝试从映射表中获取，如果没有则返回原字段名
  return fieldLabelC || fieldPath.split('.').pop() || fieldPath
}

// 动态设置高度
const setAnnotationHeight = () => {
  nextTick(() => {
    if (annotationRef.value) {
      // 获取父容器或相邻表单的高度
      const parentElement = annotationRef.value.parentElement
      if (parentElement) {
        // 查找左侧表单容器
        const formContainer =
          parentElement.querySelector('.form-container') ||
          parentElement.querySelector('.el-form') ||
          parentElement.querySelector('[class*="form"]')

        if (formContainer) {
          const formHeight = formContainer.offsetHeight
          annotationRef.value.style.height = `${formHeight}px`
        } else {
          // 如果找不到表单容器，使用父容器高度
          const parentHeight = parentElement.offsetHeight
          if (parentHeight > 0) {
            annotationRef.value.style.height = `${parentHeight}px`
          }
        }
      }
    }
  })
}

// 监听窗口大小变化
const handleResize = () => {
  setAnnotationHeight()
}

onMounted(() => {
  setAnnotationHeight()
  window.addEventListener('resize', handleResize)

  // // 使用 MutationObserver 监听 DOM 变化
  // const observer = new MutationObserver(() => {
  //   setAnnotationHeight()
  // })

  // if (annotationRef.value?.parentElement) {
  //   observer.observe(annotationRef.value.parentElement, {
  //     childList: true,
  //     subtree: true,
  //     attributes: true,
  //     attributeFilter: ['style', 'class']
  //   })
  // }
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

defineExpose({
  checkChange,
  setAnnotationHeight,
})
</script>

<style scoped lang="scss">
.annotation {
  width: 380px;
  margin-left: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;

  .annotation-header {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }

  .annotation-content {
    flex: 1;
    padding: 16px 10px;
    overflow-y: auto;

    .annotation-category {
      margin-bottom: 20px;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      padding: 10px;

      &:last-child {
        margin-bottom: 0;
      }

      .category-title {
        font-size: 14px;
        font-weight: 500;
        color: #666;
        margin-bottom: 12px;
        padding-bottom: 8px;
        border-bottom: 1px solid #f5f5f5;
      }
    }

    .annotation-item {
      display: flex;
      margin-bottom: 16px;
      padding: 12px;
      background: #fafafa;
      border-radius: 8px;
      border-left: 3px solid #e6f7ff;

      &:last-child {
        margin-bottom: 0;
      }

      .user-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #ff6b6b;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        flex-shrink: 0;

        .el-icon {
          color: white;
          font-size: 18px;
        }
      }

      .annotation-detail {
        flex: 1;

        .username {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          margin-right: 12px;
        }

        .timestamp {
          font-size: 12px;
          color: #999;
          flex: 1;
          text-align: right;
          margin: 6px 0;
        }

        .annotation-text {
          font-size: 13px;
          color: #666;
          line-height: 1.6;
          display: flex;
          flex-direction: column;
          gap: 6px;

          .old-value,
          .new-value {
            .value {
              max-height: 100px;
              overflow-y: auto;
            }
          }

          .old-value {
            display: flex;
            align-items: center;
            text-decoration: line-through;
            color: #ff4d4f;
            background: linear-gradient(135deg, rgba(255, 77, 79, 0.1), rgba(255, 77, 79, 0.05));
            padding: 6px 10px;
            border-radius: 6px;
            border: 1px solid rgba(255, 77, 79, 0.2);
            font-size: 12px;
            font-weight: 500;
            position: relative;
            box-shadow: 0 1px 2px rgba(255, 77, 79, 0.1);
            overflow: hidden;

            .error {
              font-size: 12px;
              color: #ff7875;
              font-weight: 600;
              text-decoration: none;
              margin-top: -1px;
              margin-right: 2px;
            }

            &:hover {
              background: linear-gradient(135deg, rgba(255, 77, 79, 0.15), rgba(255, 77, 79, 0.08));
              transform: translateY(-1px);
              box-shadow: 0 2px 4px rgba(255, 77, 79, 0.15);
            }
          }

          .new-value {
            display: flex;
            align-items: center;
            color: #52c41a;
            background: linear-gradient(135deg, rgba(82, 196, 26, 0.1), rgba(82, 196, 26, 0.05));
            padding: 6px 10px;
            border-radius: 6px;
            border: 1px solid rgba(82, 196, 26, 0.2);
            font-size: 12px;
            font-weight: 500;
            position: relative;
            box-shadow: 0 1px 2px rgba(82, 196, 26, 0.1);
            overflow: hidden;

            .success {
              font-size: 12px;
              color: #73d13d;
              font-weight: 600;
              margin-top: -1px;
              margin-right: 2px;
            }

            &:hover {
              background: linear-gradient(135deg, rgba(82, 196, 26, 0.15), rgba(82, 196, 26, 0.08));
              transform: translateY(-1px);
              box-shadow: 0 2px 4px rgba(82, 196, 26, 0.15);
            }
          }
        }
      }
    }

    .no-data {
      text-align: center;
      color: #999;
      font-size: 14px;
      padding: 20px 0;
      margin-top: 20px;
    }
  }
  .scroll {
    /* 滚动条样式 - 浅色 */
    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.03);
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 3px;

      &:hover {
        background: rgba(0, 0, 0, 0.06);
      }
    }
  }
}
</style>
